/**
 * 功能:代销单 控制器类
 * 开发人员:daniel.yan
 * 创建时间:2012/4/30 11:48:58
 */
package com.towker.frame.controller.sell;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.towker.web.MyRequest;
import com.towker.core.page.PageModel;
import com.towker.core.page.PageNav;
import com.towker.core.util.CollectionUtil;
import com.towker.core.util.RefGoodsType;
import com.towker.core.util.StringUtil;
import com.towker.frame.controller.BaseController;
import com.towker.frame.model.basicData.Customs;
import com.towker.frame.model.basicData.Goods;
import com.towker.frame.model.sell.Consignment;
import com.towker.frame.model.sell.InvoiceAttachment;
import com.towker.frame.model.sell.RefGoods;
import com.towker.frame.model.warehouse.InWarehouse;
import com.towker.frame.model.warehouse.SendBills;
import com.towker.frame.model.warehouse.WarehouseAccounts;
import com.towker.frame.service.basicData.CompaniesService;
import com.towker.frame.service.basicData.CustomsService;
import com.towker.frame.service.basicData.DepartmentsService;
import com.towker.frame.service.basicData.DepotsService;
import com.towker.frame.service.basicData.GoodsService;
import com.towker.frame.service.basicData.SellInvoiceMosService;
import com.towker.frame.service.sell.ConsignmentService;
import com.towker.frame.service.sell.OrderService;
import com.towker.frame.service.sell.RefGoodsService;
import com.towker.frame.service.sell.SellLineService;
import com.towker.frame.service.warehouse.SendBillsService;
import com.towker.frame.service.warehouse.WarehouseAccountsService;
import com.towker.frame.share.sys.user.UserShare;

//代销单
@Controller
@SuppressWarnings("unchecked")
@RequestMapping("/manage/sell")
public class ConsignmentController extends BaseController
{
	private ConsignmentService service;
	private DepartmentsService departmentsService;
	private DepotsService depotsService;
	private OrderService orderService;
	private GoodsService goodsService;//物品信息
	private WarehouseAccountsService warehouseAccountsService;
	private CustomsService customsService;//客户信息
	private SendBillsService sendBillsService;
	private SellInvoiceMosService sellInvoiceMosService;
	private SellLineService sellLineService;
	private CompaniesService companiesService;
	
	//业务对象注入
	public void setConsignmentService(ConsignmentService service)
	{
		this.service = service;
	}
	public void setDepartmentsService(DepartmentsService departmentsService) {
		this.departmentsService = departmentsService;
	}
	
	public void setDepotsService(DepotsService depotsService) {
		this.depotsService = depotsService;
	}
	
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}
	
	public void setGoodsService(GoodsService goodsService)
	{
		this.goodsService = goodsService;
	}
	
	public void setWarehouseAccountsService(WarehouseAccountsService warehouseAccountsService)
	{
		this.warehouseAccountsService = warehouseAccountsService;
	}
	
	public void setSendBillsService(SendBillsService sendBillsService)
	{
		this.sendBillsService = sendBillsService;
	}
	
	public void setCustomsService(CustomsService customsService)
	{
		this.customsService = customsService;
	}
	
	public void setSellInvoiceMosService(SellInvoiceMosService sellInvoiceMosService) {
		this.sellInvoiceMosService = sellInvoiceMosService;
	}
	public void setSellLineService(SellLineService sellLineService) {
		this.sellLineService = sellLineService;
	}
	public void setCompaniesService(CompaniesService companiesService)
	{
		this.companiesService = companiesService;
	}
	//添加
	@RequestMapping("/addConsignment{viewName}")
	public ModelAndView addConsignment(HttpServletRequest request, HttpServletResponse response, Consignment po, @PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName))
		{
			result = new ModelAndView();
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("dep_code", UserShare.getCurrentUserDepCode(request));
			result.addObject("deportList", deportList);
			result.addObject("sellLines", sellLineService.getList(map));
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			result.addObject("customCodes", customCodes);
			result.setViewName("/manage/sell/addConsignment.jsp");
		}
		else if ("2".equals(viewName))
		{
			PrintWriter writer = response.getWriter();
			try
			{
				po.setConsignment_code(service.getNewConsignmentCode());
				if (StringUtils.isBlank(po.getOrder_sn())) {
					po.setOrder_sn(po.getConsignment_code());
				}
				po.setOrder_id(orderService.getOrderIdBySN(po.getOrder_sn()));
				po.setAuthCoCode(UserShare.getCurrentUserCoCode(request));
				//po.setAuthDepCode(UserShare.getCurrentUserDepCode(request));
				
				service.add(po);
				String goodsInfo = req.getString("goodsInfo");
				processRefGoods(request, RefGoodsType.CONSIGNMENT_GOODS, po.getId(), goodsInfo);
				writer.write("添加代销单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("添加代销单失败！" + e.getCause());
			}
		}
		return result;
	}

	//删除
	@RequestMapping("/delConsignment")
	public void delConsignment(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		MyRequest req = new MyRequest(request);
		service.delByIds(CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0)));
		response.sendRedirect(req.getRefererURL());
	}

	//修改
	@RequestMapping("/updConsignment{viewName}")
	public ModelAndView updConsignment(HttpServletRequest request, HttpServletResponse response, Consignment po, @PathVariable String viewName) throws IOException
	{
		MyRequest req = new MyRequest(request);
		ModelAndView result = null;
		if ("1".equals(viewName))
		{
			Long id = req.getLong("keyIndex");
			po = service.getById(id);
			result = new ModelAndView();
			result.addObject("po", po);
			Map map = new HashMap();
			List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
			List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
			result.addObject("departList", departList);
			result.addObject("deportList", deportList);
			List<Customs> customCodes= customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));
			result.addObject("customCodes", customCodes);
			if (id>0) {
				List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.CONSIGNMENT_GOODS.getValue(), new Integer(String.valueOf(id)));
				result.addObject("refGoods", refGoods);
			}
			result.addObject("sellLines", sellLineService.getList(map));
			result.setViewName("/manage/sell/updConsignment.jsp");
		}
		else if ("2".equals(viewName))
		{
			String goodsInfo = req.getString("goodsInfo");
			PrintWriter writer = response.getWriter();
			try
			{
				service.update(po);
				processRefGoods(request, RefGoodsType.CONSIGNMENT_GOODS, po.getId(), goodsInfo);
				writer.write("修改代销单成功！");
			}
			catch (Exception e)
			{
				e.printStackTrace();
				writer.write("修改代销单失败！" + e.getCause());
			}
		}
		return result;
	}

	//获得分页
	@RequestMapping("/getConsignment")
	public ModelAndView getConsignment(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		//只查询当前用户所属部门
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<Consignment> pageModel = service.getPage(page, pageSize, map);
		for(int i=0;i<pageModel.getResult().size();i++){
			String code = pageModel.getResult().get(i).getCustom_code();
			pageModel.getResult().get(i).setCustoms_name(customsService.getCustomName(false, 0, code));
		}
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		result.setViewName("/manage/sell/getConsignment.jsp");
		return result;
	}
	
	
	//获得已经审核通过并未复制的发货单分页
	@RequestMapping("/getCopyConsigSendBills")
	public ModelAndView getSendBills(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="page", defaultValue="1")int page)
	{
		int pageSize = 10;
		MyRequest req = new MyRequest(request);
		Map map = req.getParameterValueMap(false, true);
		map.put("audit_status", "1");
		map.put("copy_status", "0");
		map.put("authCoCode", UserShare.getCurrentUserCoCode(request));
		//map.put("authDepCode", UserShare.getCurrentUserDepCode(request));
		PageModel<SendBills> pageModel = sendBillsService.getPage(page, pageSize, map);
		ModelAndView result = new ModelAndView();
		PageNav pageNav = new PageNav(request, pageModel);
		result.addObject("pageModel", pageModel);
		result.addObject("pageNav", pageNav);
		Map custMap = new HashMap();
		List customsList = customsService.findByCoCode(UserShare.getCurrentUserCoCode(request));// 客户信息
		result.addObject("customsList", customsList);
		result.addObject("sellLines", sellLineService.getList(new HashMap()));
		result.addObject("mos_codes", sellInvoiceMosService.getList(new HashMap()));
		result.addObject("co_code", UserShare.getCurrentUserCoCode(request)+"["+UserShare.getCurrentUserCoName(request)+"]");
		result.addObject("sell_dep_code", UserShare.getCurrentUserDepCode(request));
		Map parMap = new HashMap();
		List departList = departmentsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//部门信息
		List deportList = depotsService.findByCoCode(UserShare.getCurrentUserCoCode(request));//仓库信息
		List companiesList = companiesService.getList(parMap);
		Map nullMap = new HashMap();
		result.addObject("sellLines", sellLineService.getList(nullMap));
		result.addObject("departList", departList);
		result.addObject("deportList", deportList);
		result.addObject("companiesList",companiesList);
		result.setViewName("/manage/sell/getCopyConsigSendBills.jsp");
		return result;
	}
	
	
	//批量复制数据
	@RequestMapping("/copyConsignment")
	public void copyData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//ModelAndView result = new ModelAndView();
		MyRequest req = new MyRequest(request);
		Date consignments_date = req.getDate("consignments_date");
		String sell_dep_code = req.getString("sell_dep_code");
		String depot_code = req.getString("depot_code");
		String sell_line = req.getString("sell_line");
		String acc_period = req.getString("acc_period");
		String co_code = req.getString("co_code");
		Long[] idArry = CollectionUtil.toLongArray(req.getLongArray("keyIndex", 0));
		for (int i = 0; i < idArry.length; i++) {
			Long id = idArry[i];
			SendBills po  = sendBillsService.getById(id);
		//2.复制到代销单
			po.setCopy_status(1);
			sendBillsService.update(po);
			Consignment consignment = new Consignment();
			consignment.setSell_line(sell_line);
			consignment.setConsignment_code(service.getNewConsignmentCode());//代销单号
			consignment.setOrder_sn(po.getOrder_sn());//所属订单号
			consignment.setCustom_code(po.getCustom_code());//客户代码
			consignment.setCreate_date(new Date());//制单时间
			consignment.setAcc_period(acc_period);//财务核算期
			consignment.setDep_code(sell_dep_code);//销售部门代码
			consignment.setDepot_code(depot_code);//c仓库代码
			consignment.setCreate_code(UserShare.getCurrentUserCode(request));//制单人员代码（当前用户）
			consignment.setAuthCoCode(po.getAuthCoCode());//所属公司代码
			//consignment.setAuthDepCode(po.getAuthDepCode());//所属部门代码
			consignment.setConsignments_date(consignments_date);
			service.add(consignment);
			List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.SENDBILL_GOODS.getValue(), po.getId());
			for (RefGoods refGoods2 : refGoods) {
				refGoods2.setInfo_id(consignment.getId());
				refGoods2.setInfo_type(RefGoodsType.CONSIGNMENT_GOODS.getValue());
				refGoodsService.add(refGoods2);
			}
		}
		PrintWriter writer = response.getWriter();
		writer .write("复制发货单成功！");
	}
	

	//明细
	@RequestMapping("/getConsignmentById")
	public ModelAndView getConsignmentById(HttpServletRequest request, HttpServletResponse response)
	{
		Consignment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		ModelAndView result = new ModelAndView();
		result.addObject("po", po);
		
		result.addObject("dep", departmentsService.getByCode(po.getDep_code()));
		result.addObject("depot", depotsService.getByCode(po.getDepot_code()));
		result.addObject("customs_name", customsService.getCustomName(false, 0, po.getCustom_code()));
		List<RefGoods> refGoods = refGoodsService.getByInfoType(RefGoodsType.CONSIGNMENT_GOODS.getValue(), new Integer(String.valueOf(id)));
		result.addObject("refGoods", refGoods);
		result.setViewName("/manage/sell/getConsignmentById.jsp");
		return result;
	}
	
	
	//审核
	@RequestMapping("/auditConsignment{viewName}")
	public ModelAndView auditInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		Consignment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		po.setCustoms_name(customsService.getCustomName(false, 0, po.getCustom_code()));
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("audit", "audit");
			result.addObject("po", po);
			result.setViewName("/manage/sell/getConsignmentById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.CONSIGNMENT_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setStatus(1);
				service.update(po);
				writer.write("审核成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("审核失败！" + e.getCause());
			}
		}
		return result;
	}
	
	/*//记账
	@RequestMapping("/accConsignment{viewName}")
	public ModelAndView accInWarehouse(HttpServletRequest request, HttpServletResponse response,@PathVariable String viewName) throws IOException
	{
		ModelAndView result = null;
		Consignment po = null;
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("keyIndex");
		po = service.getById(id);
		if("1".equals(viewName)){
			result = new ModelAndView();
			result.addObject("acc", "acc");
			result.addObject("po", po);
			result.setViewName("/manage/sell/getConsignmentById.jsp");
			result.addObject("refGoods", refGoodsService.getByInfoType(RefGoodsType.CONSIGNMENT_GOODS.getValue(),new Integer(String.valueOf(id)) ));
		}else if("2".equals(viewName)) {
			PrintWriter writer = response.getWriter();
			try {
				po.setStatus(3);
				service.update(po);//更新状态
				List<RefGoods> refgoodList = refGoodsService.getByInfoType(RefGoodsType.CONSIGNMENT_GOODS.getValue(), po.getId());
				if (refgoodList!=null && refgoodList.size()!=0) {
					for (int i = 0; i < refgoodList.size(); i++) {
						RefGoods refGoods = (RefGoods)refgoodList.get(i);
						Goods goods = goodsService.getById(new Long(refGoods.getGoods_id()));
						*//**
						 * 记录到仓库帐中
						 *//*
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						WarehouseAccounts warehouseAccounts = new WarehouseAccounts();
						warehouseAccounts.setAcc_period(po.getAcc_period());//财务统计核算期
						warehouseAccounts.setInfo_type("代销单");//仓库帐类型
						warehouseAccounts.setGoods_sn(goods.getGoods_sn());//物料代码
						warehouseAccounts.setDep_code(po.getDepot_code());//仓库代码
						warehouseAccounts.setCreate_date(format.format(po.getCreate_date()));//入仓单日期
						warehouseAccounts.setCreate_time(format.format(po.getCreate_time()));//入仓库时间
						warehouseAccounts.setSys_date(format.format(new Date()));//生成仓库帐时间
						warehouseAccounts.setAmount(refGoods.getAmount());//物品数量
						warehouseAccounts.setStock_num(goods.getStock());//当前库存数量
						//warehouseAccounts.setSend_amount(0);//已下采购单要求送货数量, 根据采购单号 查询采购数量
						String remark = "单号："+po.getConsignment_code()+"，部门："+po.getDep_code()+"";
						warehouseAccounts.setRemark(remark);//凭证号（单号）、部门、客户等>
						warehouseAccountsService.add(warehouseAccounts);
					}
				}
				writer.write("记账成功！");
			}catch (Exception e) {
				e.printStackTrace();
				writer.write("记账失败！" + e.getCause());
			}
		}
		return result;
	}*/
	
	
}
